<template>
  <el-dialog :close-on-click-modal="false" modal-append-to-body lock-scroll top="10%" :title="$t('km.addCataInformation')" :visible.sync="dialogAddFormVisible" width="50%">
    <label > {{$t('km.catalogueName')}}</label>
    <el-input size="mini" style="width:100%" v-model.trim="catalogue"></el-input>
    <operate-dep ref="dep" v-show="kmType=== 'inner' && flag === 'kf'" style="padding-top: 10px" :showAgents='[]'></operate-dep>
    <div slot="footer" class="dialog-footer">
      <el-button @click.stop="dialogAddFormVisible = false" class="primary_btn">{{$t('public.cancel')}}</el-button>
      <el-button type="primary" @click.stop="confirmName" class="primary_btn">{{$t('public.confirm')}}</el-button>
    </div>
  </el-dialog>
</template>
<script>
  import operateDep from './operateDep'
  export default {
    name: 'AddCatalogue',
    data () {
      return {
        flag: this.$store.getters.isEcommerce ? 'ecommerce' : 'kf',
        dialogAddFormVisible: false,
        catalogue: '',
        formLabelWidth: '120px'
      }
    },
    props: {
      pid: String,
      kmType: String
    },
    components: {
      operateDep
    },
    methods: {
      stop () {
        return false
      },
      open () {
        this.catalogue = ''
        this.dialogAddFormVisible = true
        this.$nextTick(() => {
          this.kmType === 'inner' && this.$refs.dep.reset()
        })
      },
      confirmName () {
        if (this.catalogue === '') {
          this.$message.error(this.$t('km.catalogueNameCantBeEmpty'))
          return
        } else if (this.catalogue.length > 25) {
          this.$message.error(this.$t('km.catalogueNameTooLong'))
          return
        }
        let data = {
          name: this.catalogue,
          pid: this.pid,
          order: 0,
          showDepartment: this.kmType === 'inner' ? this.$refs.dep.save()[1] : [],
          showAgents: this.kmType === 'inner' ? this.$refs.dep.save()[0] : [],
          kmType: this.kmType
        }
        if (data.showDepartment.length === 0) {
          delete data.showDepartment
        }
        if (data.showAgents.length === 0) {
          delete data.showAgents
        }
        this.$store.dispatch('addCatalog', data).then((rep) => {
          if (rep.success) {
            this.$message.success(this.$t('km.addCatalogueSuccess'))
            this.$store.commit('km/REFRESH_TREE', Math.random())
            this.dialogAddFormVisible = false
          } else if (rep.code === '1001') {
            this.dialogAddFormVisible = true
          }
        })
      }
    }
  }
</script>
<style lang="stylus" scoped>
  .addCataForm
    display inline
    padding-right 0
    .icon-zhankai
      padding 0px 6px
  .sort
    width 130px
    float left
</style>

